<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\facade\Mns;
use app\models\{Annou, Banner, News, Riderlist, Region, Config, Wechat};
use think\facade\Log;


use think\Db;

class Other extends Base
{

    //回调结果
    public function callback()
    {

        $result = (new Wechat())->callback();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    public function getptdatas()
    {
        $ptdatas = (new Config())->where('key_value', 'ptdatas')->value('value');
        $ptdatas = json_decode($ptdatas, true);
        if (!empty($ptdatas['orderuser'])) {
            unset($ptdatas['orderuser']);
        }
        $ptdatas['userlists'] = [];
        $lists = Redis::lRange('ptdatas_lists', 0, 30);
        foreach ($lists as $list) {
            $ptdatas['userlists'][] = unserialize($list);
        }
        $this->result($ptdatas, 0, '获取成功');
    }

    public function Annou()
    {
        $type = $this->request->get('type/d', 1);
        $list = (new Annou())->order('dates desc')->where('type', $type)->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    public function Banner()
    {
        $list = (new Banner())->select();
        $this->result($list, 0, '获取成功');
    }

    public function News()
    {
        $type = $this->request->get('type/d', 1);
        $list = (new News())->order('dates desc')->where('type', $type)->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '获取成功');
    }

    //发送短信
    public function sendMns()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
        ], [
            'mobile.require' => '手机号码必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
        if (empty($user)) {
            $this->result([], 1, '您还不是家政');
        }
        $CheckCode = (new Mns())->send($data['mobile']);
        if (!$CheckCode) {
            $this->result([], 1, $CheckCode['msg']);
        }
        $this->result([], 0, $CheckCode['msg']);
    }

    public function uploads()
    {
        if ($this->request->isPost()) {
            $file = request()->file('file');
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 5, 'ext' => 'jpg,png,gif,jpeg'])
                ->move($path);
            if (!$info) {
                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . $info->getSaveName();
                $url = url($url, '', '', false);
                $url = "https://" . Env('app.api_url') . $url;
                $this->result($url, 0, '上传成功');
            }
        }
    }

    public function geocoder()
    {
        $key = '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT';
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            Log::write($data, 'weizhi');

            $url = 'https://restapi.amap.com/v3/geocode/regeo?location=' . $data['lng'] . ',' . $data['lat'] . '&key=ac9bfdc24e033d01cf7b18cd9a15ffca';
            $res = getData($url);
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败');
                }
                $results = $res['regeocode']['addressComponent'];
                $resuls = [
                    "nation_code" => 156,
                    "adcode" => $results['adcode'] ?? 0,
                    "city_code" => "156" . $results['adcode'] ?? 0,
                    "name" => "中国," . $results['province'] . ',' . $results['city'] . ',' . $results['district'],
                    "location" => [
                        "lat" => $data['lat'],
                        "lng" => $data['lng']
                    ],
                    "nation" => "中国",
                    "province" => $results['province'] ?? '',
                    "city" => $results['city'] ?? '',
                    "district" => $results['district'] ?? '',
                    "street" => 0,
                    "street_title" => $results['township'] ?? ''
                ];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'], 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                Log::write($results, 'weizhi');

                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 1, ['key' => $key]);
        }
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }
}